package RIP;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Esta classe eh responssavel pelos servidores que estaram "escutando" em cada node
 */
public class serverMulthreadTCP extends Thread {

    private ServerSocket welcomeSocket;
    private ArrayList<pacote> rcvPacotes;

    public serverMulthreadTCP(int porta) throws IOException {
        welcomeSocket = new ServerSocket(porta);
        rcvPacotes = new ArrayList<pacote>();
    }

    public void run() {
        Socket connectionSocket = null;

        ObjectInputStream inFromClient = null;

        while (true) {
            try {
                connectionSocket = getWelcomeSocket().accept();
                inFromClient = new ObjectInputStream(connectionSocket.getInputStream());
                pacote pacoteCliente = (pacote) inFromClient.readObject();

                rcvPacotes.add(pacoteCliente);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(serverMulthreadTCP.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(serverMulthreadTCP.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public ServerSocket getWelcomeSocket() {
        return welcomeSocket;
    }

    // this is MAGIC..... 
    public ArrayList<pacote> getRcvPacotes() throws InterruptedException {

        int seconds = 0;
        while (rcvPacotes.isEmpty()) {
            Thread.sleep(1000);
            seconds++;
        }


        ArrayList<pacote> p = new ArrayList<pacote>();
        for (pacote pacoteLista : rcvPacotes) {
            p.add(new pacote(pacoteLista.getSourceid(), pacoteLista.getDestid(), pacoteLista.getDistanceTable()));
        }
        rcvPacotes.clear();
        return p;
    }
}
